package com.dylan.netty.bio.socket;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;

/**
 * @author zhangshaojian
 * @date 2022/8/9 14:43
 */
@Slf4j
public class Client {
    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            connectionSocket();
        }
    }

    private static void connectionSocket() {
        try (
                Socket socket = new Socket("localhost", 8888);
                BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))
        ) {
            log.info("连接服务器成功，端口" + 8888);

            writer.write(new String(Files.readAllBytes(Paths.get("D:\\121.txt"))));
            writer.flush();
            // 关闭输出流，在socket read到没内容的时候才会返回-1、并不继续阻塞程序
            socket.shutdownOutput();
            String content = reader.lines().collect(Collectors.joining("\n"));
            log.info("收到服务器消息：");
            log.info(content);
        } catch (Exception ex) {
            log.error("连接出现错误！！！！");
        } finally {
            log.info("结束通信！！！");
        }
    }
}
